package com.itheima.demo;

import com.itheima.domain.Classes;
import com.itheima.domain.Course;
import com.itheima.domain.Person;
import com.itheima.domain.Student;
import com.itheima.mapper.Some2SomeMapper;
import com.itheima.utils.MapperUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;


public class Anno_Some2SomeDemo {
    //获取工具类对象
    MapperUtils mapperUtils = new MapperUtils();

    public static SqlSession sqlSession;
    public static Some2SomeMapper mapper;

    @Before
    public void before() {
        //通过工具类获取SqlSession对象
        sqlSession = mapperUtils.getSqlSession("MyBatisConfig.xml");
        mapper = sqlSession.getMapper(Some2SomeMapper.class);
        System.out.println("===========================");
    }

    @After
    public void after() {
        System.out.println("===========================");
        //释放资源
        mapperUtils.closeResource();
    }


    @Test
    public void findAll() {
        List<Person> list = mapper.findAll();
        for (Person person : list) {
            System.out.println(person);
        }
    }

    //查找班级及其学生
    @Test
    public void findClasses() {
        List<Classes> classes = mapper.findClasses();
        for (Classes c : classes) {
            System.out.println(c.getName());
            //使用懒加载  当需要关联表数据时, 才执行sql语句
            List<Student> stuList = c.getStuList();
            for (Student student : stuList) {
                System.out.println("\t" + student.getName());
            }
        }
    }

    //查找学生和所学课程
    @Test
    public void findStudents() {
        List<Student> students = mapper.findStudents();
        for (Student student : students) {
            System.out.println(student.getName());
            List<Course> courses = student.getCourses();
            for (Course c : courses) {
                System.out.println("\t" + c.getName());
            }
        }
    }
}
